package com.softstao.guoyu.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.softstao.guoyu.R;
import com.softstao.guoyu.accept.Accept;
import com.softstao.guoyu.base.BaseActivity;
import com.softstao.guoyu.global.APIInterface;
import com.softstao.guoyu.global.SharePreferenceManager;
import com.softstao.guoyu.global.UserManager;
import com.softstao.guoyu.model.Image;
import com.softstao.guoyu.model.WechatLogin;
import com.softstao.guoyu.model.me.AgentId;
import com.softstao.guoyu.mvp.events.NetWorkEvent;
import com.softstao.guoyu.mvp.interactor.LaunchInteractor;
import com.softstao.guoyu.mvp.interactor.LoginInteractor;
import com.softstao.guoyu.mvp.presenter.LaunchPresenter;
import com.softstao.guoyu.mvp.presenter.LoginPresenter;
import com.softstao.guoyu.mvp.viewer.LaunchViewer;
import com.softstao.guoyu.mvp.viewer.LoginViewer;
import com.softstao.guoyu.utils.CProgressDialogUtils;
import com.softstao.guoyu.utils.HProgressDialogUtils;
import com.softstao.guoyu.utils.UpdateAppHttpUtils;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.vector.update_app.UpdateAppBean;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.UpdateCallback;
import com.vector.update_app.service.DownloadService;
import com.vector.update_app.utils.AppUpdateUtils;
import com.wangjie.androidinject.annotation.annotations.mvp.AIPresenter;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;


public class WelcomeActivity extends BaseActivity implements LaunchViewer, LoginViewer {

    @AIPresenter(presenter = LaunchPresenter.class, interactor = LaunchInteractor.class)
    LaunchPresenter presenter;
    @AIPresenter(presenter = LoginPresenter.class, interactor = LoginInteractor.class)
    LoginPresenter loginPresenter;

    @BindView(R.id.seconds)
    TextView seconds;
    @BindView(R.id.img)
    ImageView img;
    @BindView(R.id.img1)
    ImageView img1;
    @BindView(R.id.image_view)
    RelativeLayout imageView;
    private int count = 5;
    private boolean is_can = true;
    private boolean isShowDownloadProgress;
    private AlertDialog dialog;

    @Override
    public int _ContentView() {
        return R.layout.activity_welcome;
    }

    @Override
    public void initView() {
        tintManager.setStatusBarTintColor(Color.TRANSPARENT);
        new RxPermissions(this).request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(result -> {
                    if (result) {
                        updateApp();
                    }
                });
    }

    private void welcome() {
        if (SharePreferenceManager.getInstance().isFirstIn()) {
            imageView.setVisibility(View.GONE);
            img1.setVisibility(View.VISIBLE);
            SharePreferenceManager.getInstance().setFirstIn(false);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (UserManager.getInstance().getUser() == null) {
                        startActivity(new Intent(context, LoginActivity.class));
                        finish();
                    } else if (SharePreferenceManager.getInstance().getAgentId() == 0) {
                        startActivity(new Intent(context, LoginActivity.class));
                        finish();
                    } else {
                        if (SharePreferenceManager.getInstance().getLoginInfo() != null
                                && !TextUtils.isEmpty(SharePreferenceManager.getInstance().getLoginInfo().getUsername())
                                && !TextUtils.isEmpty(SharePreferenceManager.getInstance().getLoginInfo().getPassword())) {
                            askLogin();
                        } else {
                            startActivity(new Intent(context, LoginActivity.class));
                            finish();
                        }
                    }
                }
            }, 1000);
        } else {
            img1.setVisibility(View.GONE);
            imageView.setVisibility(View.VISIBLE);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    launch();
                }
            }, 2000);
        }
    }

    private void updateApp() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("apptype", "android");
        new UpdateAppManager.Builder()
                .setActivity(this)
                .setUpdateUrl(APIInterface.UPDATE_APP)
                .setHttpManager(new UpdateAppHttpUtils())
                .setPost(false)
                .setTopPic(R.mipmap.update_bg)
                .setParams(params)
                .setTargetPath(Environment.getExternalStorageDirectory().getAbsolutePath())
                .hideDialogOnDownloading(false)
                .build()
                .checkNewApp(new UpdateCallback() {
                    @Override
                    protected UpdateAppBean parseJson(String json) {
                        UpdateAppBean updateAppBean = new UpdateAppBean();
                        try {
                            JSONObject jsonObject = new JSONObject(json);
                            String isUpdate;
                            boolean isForce;
                            long size;
                            String target_size = null;
                            if (TextUtils.isEmpty(jsonObject.opt("data").toString()) == false && !jsonObject.opt("data").toString().equals("{}")) {
                                JSONObject data_json = new JSONObject(jsonObject.opt("data").toString());
                                if (data_json.optInt("versionCode") <= AppUpdateUtils.getVersionCode(context)) {
                                    isUpdate = "No";
                                } else {
                                    isUpdate = "Yes";
                                }
                                if (data_json.optInt("isForce") == 0) {
                                    isForce = false;
                                } else {
                                    isForce = true;
                                }
                                size = data_json.optLong("packageSize");
                                if (size < 1024) {
                                    target_size = String.valueOf(size) + "KB";
                                } else {
                                    size = size / 1024;
                                }
                                if (size < 1024) {
                                    //因为如果以MB为单位的话，要保留最后1位小数，
                                    //因此，把此数乘以100之后再取余
                                    size = size * 100;
                                    target_size = String.valueOf((size / 100)) + "."
                                            + String.valueOf((size % 100)) + "MB";
                                }
                                updateAppBean
                                        //（必须）是否更新Yes,No
                                        .setUpdate(isUpdate)
                                        //（必须）新版本号，
                                        .setNewVersion(data_json.optString("version"))
                                        //（必须）下载地址
                                        .setApkFileUrl(data_json.optString("packageUrl"))
                                        //测试下载路径是重定向路径
//                                    .setApkFileUrl("http://openbox.mobilem.360.cn/index/d/sid/3282847")
                                        //（必须）更新内容
                                        .setUpdateLog(data_json.optString("description"))
                                        //测试内容过度
//                                    .setUpdateLog("1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16")
                                        //大小，不设置不显示大小，可以不设置
                                        .setTargetSize(target_size)
                                        //是否强制更新，可以不设置
                                        .setConstraint(isForce);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            welcome();
                        }
                        return updateAppBean;
                    }

                    @Override
                    protected void hasNewApp(UpdateAppBean updateApp, UpdateAppManager updateAppManager) {
                        //自定义对话框
                        isShowDownloadProgress = true;
                        showDiyDialog(updateApp, updateAppManager);
                    }

                    /**
                     * 网络请求之前
                     */
                    @Override
                    public void onBefore() {
                        CProgressDialogUtils.showProgressDialog(WelcomeActivity.this);
                    }

                    /**
                     * 网路请求之后
                     */
                    @Override
                    public void onAfter() {
                        CProgressDialogUtils.cancelProgressDialog(WelcomeActivity.this);
                    }

                    /**
                     * 没有新版本
                     */
                    @Override
                    public void noNewApp() {
                        welcome();
                    }
                });
    }

    /**
     * 自定义对话框
     *
     * @param updateApp
     * @param updateAppManager
     */
    private void showDiyDialog(final UpdateAppBean updateApp, final UpdateAppManager updateAppManager) {
        dialog = new AlertDialog.Builder(this, R.style.MyDialog).create();
        dialog.setCanceledOnTouchOutside(false);
        View view = getLayoutInflater().inflate(R.layout.layout_update_dialog, null);
        dialog.setView(view);
        ((TextView) view.findViewById(R.id.title)).setText(String.format("是否升级到%s版本？", updateApp.getNewVersion()));
        ((TextView) view.findViewById(R.id.package_size)).setText("新版本大小：" + updateApp.getTargetSize());
        ((TextView) view.findViewById(R.id.content)).setText(updateApp.getUpdateLog());
        view.findViewById(R.id.update_btn).setOnClickListener(v -> {
            //显示下载进度
            if (isShowDownloadProgress) {
                updateAppManager.download(new DownloadService.DownloadCallback() {
                    @Override
                    public void onStart() {
                        HProgressDialogUtils.showHorizontalProgressDialog(WelcomeActivity.this, "下载进度", false);
                    }

                    /**
                     * 进度
                     *
                     * @param progress  进度 0.00 -1.00 ，总大小
                     * @param totalSize 总大小 单位B
                     */
                    @Override
                    public void onProgress(float progress, long totalSize) {
                        HProgressDialogUtils.setProgress(Math.round(progress * 100));
                    }

                    /**
                     *
                     * @param total 总大小 单位B
                     */
                    @Override
                    public void setMax(long total) {

                    }


                    @Override
                    public boolean onFinish(File file) {
                        HProgressDialogUtils.cancel();
                        return true;
                    }

                    @Override
                    public void onError(String msg) {
                        Toast.makeText(WelcomeActivity.this, msg, Toast.LENGTH_SHORT).show();
                        HProgressDialogUtils.cancel();

                    }
                });
            } else {
                //不显示下载进度
                updateAppManager.download();
            }
            dialog.dismiss();
        });
        ImageView cancel = (ImageView) view.findViewById(R.id.cancel_btn);
        cancel.setOnClickListener(v -> {
            welcome();
            dialog.dismiss();
        });
        if (updateApp.isConstraint() == false) {
            cancel.setVisibility(View.VISIBLE);
        } else {
            cancel.setVisibility(View.GONE);
        }
        dialog.show();
    }

    private int getCount() {
        count--;
        if (count == 1) {
            if (UserManager.getInstance().getUser() == null) {
                startActivity(new Intent(context, LoginActivity.class));
                finish();
            } else if (SharePreferenceManager.getInstance().getAgentId() == 0) {
                startActivity(new Intent(context, LoginActivity.class));
                finish();
            } else {
                if (SharePreferenceManager.getInstance().getLoginInfo() != null
                        && !TextUtils.isEmpty(SharePreferenceManager.getInstance().getLoginInfo().getUsername())
                        && !TextUtils.isEmpty(SharePreferenceManager.getInstance().getLoginInfo().getPassword())) {
                    askLogin();
                } else {
                    startActivity(new Intent(context, LoginActivity.class));
                    finish();
                }
            }
        }
        return count;
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                seconds.setVisibility(View.VISIBLE);
                seconds.setText("跳过 " + getCount());
                seconds.setOnClickListener(v -> {
                    if (UserManager.getInstance().getUser() == null) {
                        startActivity(new Intent(context, LoginActivity.class));
                        finish();
                    } else if (SharePreferenceManager.getInstance().getAgentId() == 0) {
                        startActivity(new Intent(context, LoginActivity.class));
                        finish();
                    } else {
                        if (SharePreferenceManager.getInstance().getLoginInfo() != null
                                && !TextUtils.isEmpty(SharePreferenceManager.getInstance().getLoginInfo().getUsername())
                                && !TextUtils.isEmpty(SharePreferenceManager.getInstance().getLoginInfo().getPassword())) {
                            askLogin();
                        } else {
                            startActivity(new Intent(context, LoginActivity.class));
                            finish();
                        }
                    }
                    is_can = false;
                });
                if (is_can) {
                    handler.sendEmptyMessageDelayed(0, 1000);
                }
            }
        }
    };

    @Override
    public void launch() {
        presenter.launch("bootdisplay");
    }

    @Override
    public void launchResult(Image image) {
        if (!TextUtils.isEmpty(image.getImgUrl())) {
            imageView.setVisibility(View.VISIBLE);
            Glide.with(context).load(image.getImgUrl()).into(img);
            img.setOnClickListener(v -> {
                if (!TextUtils.isEmpty(image.getLinkUrl())) {
                    Intent intent = new Intent(context, WebViewActivity.class);
                    intent.putExtra("title", "详情");
                    intent.putExtra("url", image.getLinkUrl());
                    intent.putExtra("launch", "1");
                    startActivity(intent);
                    handler.removeMessages(0);
                    finish();
                }
            });
        } else {
            imageView.setVisibility(View.GONE);
        }
        handler.sendEmptyMessageDelayed(0, 1000);
    }

    @Accept
    public void netWorkError(Object tag, NetWorkEvent netWorkEvent) {
        super.netWorkError(tag, netWorkEvent);
        if (UserManager.getInstance().getUser() == null) {
            startActivity(new Intent(context, LoginActivity.class));
        } else if (SharePreferenceManager.getInstance().getAgentId() == 0) {
            startActivity(new Intent(context, LoginActivity.class));
        } else {
            Intent intent = new Intent(getContext(), MainActivity.class);
            startActivity(intent);
        }
        finish();
    }

    @Override
    protected void error(String msg) {
        super.error(msg);
        if (msg.equals("账号/密码错误，或该用户不存在")) {
            CookieSyncManager.createInstance(getApplicationContext());
            CookieManager.getInstance().removeAllCookie();
            SharePreferenceManager.getInstance().setCookie("");
            UserManager.getInstance().setUser(null);
            SharePreferenceManager.getInstance().setLoginInfo(null);
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            finish();
        } else {
            if (UserManager.getInstance().getUser() == null) {
                startActivity(new Intent(context, LoginActivity.class));
                finish();
            } else if (SharePreferenceManager.getInstance().getAgentId() == 0) {
                startActivity(new Intent(context, LoginActivity.class));
                finish();
            } else {
                if (SharePreferenceManager.getInstance().getLoginInfo() != null
                        && !TextUtils.isEmpty(SharePreferenceManager.getInstance().getLoginInfo().getUsername())
                        && !TextUtils.isEmpty(SharePreferenceManager.getInstance().getLoginInfo().getPassword())) {
                    askLogin();
                } else {
                    startActivity(new Intent(context, LoginActivity.class));
                    finish();
                }
            }
        }
    }

    @Override
    public void askLogin() {
        loginPresenter.login(SharePreferenceManager.getInstance().getLoginInfo().getUsername(),
                SharePreferenceManager.getInstance().getLoginInfo().getPassword());
    }

    @Override
    public void wechatLogin() {

    }

    @Override
    public void loginResult(AgentId agentId) {
        SharePreferenceManager.getInstance().setLogin(true);
        SharePreferenceManager.getInstance().setAgentId(agentId.getAgentId());
        Intent intent = new Intent(getContext(), MainActivity.class);
        startActivity(intent);
        count = 0;
        finish();
    }

    @Override
    public void wechatResult(WechatLogin wechatLogin) {

    }
}
